<template>
  <Tabs :animated="true" v-model:activeKey="activeKey" centered>
    <TabPane key="1" tab="LWM2M模式">
      <div class="LWM2M模式">
        <Select
          mode="multiple"
          placeholder="Please select"
          class="w-full !mb-24px"
          :disabled="isDisable"
          v-model:value="selectedLwM2MObjectsArray"
          :options="
            lwm2mList.map((optionsItem, index) => ({
              value: index,
              label: optionsItem.name + '#' + optionsItem.keyId,
            }))
          "
          @change="handleChange"
        />
        <Collapse
          v-for="LWM2MObj in selectedLwM2MObjects"
          :key="LWM2MObj.id"
          expandIconPosition="right"
          class="!mb-24px"
        >
          <CollapsePanel :header="LWM2MObj.name + '#' + LWM2MObj.keyId">
            <template #extra>
              <Button
                shape="circle"
                type="text"
                @click.stop="toEditAttribute(LWM2MObj, 1)"
                v-show="!LWM2MObj.pData?.length && !isDisable"
              >
                <Icon :icon="ICON.PLUS" class="!text-24px" />
              </Button>
              <Button
                shape="circle"
                type="text"
                @click.stop="toEditAttribute(LWM2MObj, 1)"
                v-show="LWM2MObj.pData?.length && !isDisable"
              >
                <Icon :icon="ICON.EDIT" class="!text-24px" />
              </Button>
              <Button
                shape="circle"
                type="text"
                @click.stop="toEditAttribute(LWM2MObj, 1)"
                v-show="isDisable && LWM2MObj.pData?.length"
              >
                <Icon :icon="ICON.CHECK" class="!text-24px" />
              </Button>
              <Button
                shape="circle"
                type="text"
                v-if="LWM2MObj.multiple === true && !isDisable"
                class="ml-10px"
                @click.stop="toAddInstance(LWM2MObj)"
              >
                <Icon :icon="ICON.ADDENTITY" class="!text-24px" />
              </Button>
            </template>
            <Collapse v-model:activeKey="LWM2MObj.instances.id" expandIconPosition="right">
              <CollapsePanel
                v-for="(instances, instanceIndex) in LWM2MObj.instances"
                :key="instances.id"
                :header="'实例 #' + instances.id"
              >
                <template #extra>
                  <Button
                    shape="circle"
                    type="text"
                    @click.stop="toEditAttribute(LWM2MObj, 2, instanceIndex)"
                    :disabled="isPartiallySelected(LWM2MObj, instanceIndex, 4)"
                    v-show="!instances.pData?.length && !isDisable"
                  >
                    <Icon :icon="ICON.PLUS" class="!text-24px" />
                  </Button>
                  <Button
                    shape="circle"
                    type="text"
                    @click.stop="toEditAttribute(LWM2MObj, 2, instanceIndex)"
                    :disabled="isPartiallySelected(LWM2MObj, instanceIndex, 4)"
                    v-show="instances.pData?.length && !isDisable"
                  >
                    <Icon :icon="ICON.EDIT" class="!text-24px" />
                  </Button>
                  <Button
                    shape="circle"
                    type="text"
                    @click.stop="toEditAttribute(LWM2MObj, 2, instanceIndex)"
                    :disabled="isPartiallySelected(LWM2MObj, instanceIndex, 4)"
                    v-show="disable && instances.pData?.length"
                  >
                    <Icon :icon="ICON.CHECK" class="!text-24px" />
                  </Button>
                </template>
                <Row>
                  <Col span="10">
                    <span>#ID资源名称</span>
                  </Col>
                  <Col span="2">
                    <span>属性</span>
                    <Checkbox
                      @change="allSelectChange($event, LWM2MObj, instanceIndex, 1)"
                      :indeterminate="isPartiallySelected(LWM2MObj, instanceIndex, 1)"
                      :disabled="isDisable"
                    />
                  </Col>
                  <Col span="2">
                    <span>遥测</span>
                    <Checkbox
                      @change="allSelectChange($event, LWM2MObj, instanceIndex, 2)"
                      :indeterminate="isPartiallySelected(LWM2MObj, instanceIndex, 2)"
                      :disabled="isDisable"
                    />
                  </Col>
                  <Col span="3">
                    <span>观察者</span>
                    <Checkbox
                      @change="allSelectChange($event, LWM2MObj, instanceIndex, 3)"
                      :indeterminate="isPartiallySelected(LWM2MObj, instanceIndex, 3)"
                      :disabled="isDisable"
                    />
                  </Col>
                  <Col span="6">
                    <span>键名</span>
                  </Col>
                </Row>
                <Row v-for="(resources, resourcesIndex) in instances.resources" :key="resources.id">
                  <Col span="10">
                    <span>{{ '#' + resources.id + ' ' + resources.name }}</span>
                  </Col>
                  <Col span="2">
                    <Checkbox v-model:checked="resources.attribute" :disabled="isDisable" />
                  </Col>
                  <Col span="2">
                    <Checkbox v-model:checked="resources.telemetry" :disabled="isDisable" />
                  </Col>
                  <Col span="2">
                    <Checkbox
                      v-model:checked="resources.observe"
                      :disabled="!(resources.telemetry || resources.attribute) || isDisable"
                    />
                  </Col>
                  <Col span="6">
                    <Input v-model:value="resources.keyName" :disabled="isDisable" />
                  </Col>
                  <Col span="2">
                    <Button
                      shape="circle"
                      type="text"
                      :disabled="!(resources.telemetry || resources.attribute)"
                      @click.stop="toEditAttribute(LWM2MObj, 3, instanceIndex, resourcesIndex)"
                      v-show="!resources.pData?.length && !isDisable"
                    >
                      <Icon :icon="ICON.PLUS" class="!text-24px" />
                    </Button>
                    <Button
                      shape="circle"
                      type="text"
                      :disabled="!(resources.telemetry || resources.attribute)"
                      @click.stop="toEditAttribute(LWM2MObj, 3, instanceIndex, resourcesIndex)"
                      v-show="resources.pData?.length && !isDisable"
                    >
                      <Icon :icon="ICON.EDIT" class="!text-24px" />
                    </Button>
                    <Button
                      shape="circle"
                      type="text"
                      :disabled="!(resources.telemetry || resources.attribute)"
                      @click.stop="toEditAttribute(LWM2MObj, 3, instanceIndex, resourcesIndex)"
                      v-show="isDisable && resources.pData?.length"
                    >
                      <Icon :icon="ICON.CHECK" class="!text-24px" />
                    </Button>
                  </Col>
                </Row>
              </CollapsePanel>
            </Collapse>
          </CollapsePanel>
        </Collapse>
      </div>
    </TabPane>
    <TabPane key="2" tab="BootStrap" :forceRender="true">
      <div class="BootStrapBox">
        <Checkbox
          v-model:checked="transportConfiguration.bootstrapServerUpdateEnable"
          :disabled="isDisable"
          class="!mb-24px"
        >
          包含Bootstrap Serve更新
        </Checkbox>
        <Collapse
          v-for="(server, index) in transportConfiguration.bootstrap"
          :key="index"
          expandIconPosition="right"
        >
          <CollapsePanel
            :forceRender="true"
            :header="server.bootstrapServerIs ? 'Bootstrap Server' : 'LwM2M Server'"
          >
            <template #extra>
              <Button @click="handleDel(index)" shape="circle" type="text" :disabled="isDisable">
                <Icon icon="ic:sharp-delete" class="!text-24px" />
              </Button>
            </template>
            <BasicForm @register="server.Form[0]" />
          </CollapsePanel>
        </Collapse>
        <Button
          type="primary"
          @click="addServer"
          v-show="!transportConfiguration.bootstrapServerUpdateEnable"
          :disabled="isDisable"
          class="my-24px"
          >添加LwM2M服务器</Button
        >
        <Button
          type="primary"
          v-show="transportConfiguration.bootstrapServerUpdateEnable"
          :disabled="isDisable"
          @click="toAddServer"
          class="my-24px"
          >添加服务器配置</Button
        >
      </div>
    </TabPane>
    <TabPane key="3" tab="其他设置" :forceRender="true">
      <BasicForm @register="registerSetting" />
    </TabPane>
    <TabPane key="4" tab="设备配置JSON">
      <CodeEditor v-model:value="json_string" :readonly="true" :mode="modeValue" />
    </TabPane>
  </Tabs>
  <AddNewServer @register="registerModal" @choose-type="handleChooseType" />
  <AddInstance @register="registerInstanceModal" @get-instance="addInstance" />
  <EditAttribute @register="registerEditAttribute" @get-edit="editAttribute" :disable="isDisable" />
</template>

<script setup lang="ts">
  import {
    Tabs,
    TabPane,
    Checkbox,
    Row,
    Col,
    Select,
    Input,
    Collapse,
    CollapsePanel,
    Button,
  } from 'ant-design-vue';
  import { CodeEditor, MODE } from '/@/components/CodeEditor';
  import { onMounted, ref, watch } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { SettingSchemas, LWM2MServerSchemas } from './LWM2M.data';
  import { useModal } from '/@/components/Modal';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import AddNewServer from './AddNewServer.vue';
  import AddInstance from './AddInstance.vue';
  import EditAttribute from './EditAttribute.vue';
  import _ from 'lodash';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { lwm2mParams } from '/@/api/thingsborad/profile/deviceProfile/model/deviceProfileModel';
  import { getLWM2MList } from '/@/api/thingsborad/profile/deviceProfile/deviceProfile';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  const { createConfirm } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerInstanceModal, { openModal: openInstanceModal }] = useModal();
  const [registerEditAttribute, { openModal: openEditAttributeModal }] = useModal();
  const isDisable = ref<boolean>(false);
  let activeKey = ref<any>('1');
  let lwm2mList = ref<any>([]);
  const modeValue = ref<MODE>(MODE.JSON);
  const props = defineProps({
    formData: {
      type: Object,
    },
    disable: { type: Boolean },
  });
  let emitsValue = ref<any>();
  //请求lwm2m的参数
  let params = ref<lwm2mParams>({
    pageSize: 50,
    page: 0,
    sortProperty: 'id',
    sortOrder: 'ASC',
  });
  //选中的lwm2m
  let selectedLwM2MObjects = ref<any>([]);
  //select中选择的lwm2m在lwm2m中的下标
  let selectedLwM2MObjectsArray = ref<any>([]);
  //记录所有上一次select中被选中的lwm2m在lwm2m中的下标
  let selectedLwM2MObjectsFlag = ref<any>([]);
  let transportConfiguration = ref<any>({
    type: 'LWM2M',
    bootstrapServerUpdateEnable: false,
    bootstrap: [
      {
        binding: 'U',
        bootstrapServerAccountTimeout: 0,
        bootstrapServerIs: false,
        clientHoldOffTime: 1,
        defaultMinPeriod: 1,
        host: '0.0.0.0',
        lifetime: 300,
        notifIfDisabled: true,
        port: 5686,
        securityMode: 'PSK',
        serverCertificate: '',
        serverPublicKey: '',
        shortServerId: 123,
        Form: useForm({
          schemas: LWM2MServerSchemas,
          layout: 'vertical',
          ...modalFormStyleSetting,
          showActionButtonGroup: false,
        }),
      },
    ],
    clientLwM2mSettings: [],
    observeAttr: { attribute: [], attributeLwm2m: {}, keyName: {}, observe: [], telemetry: [] },
  });
  //lwM2M Server 数据参数
  const LwM2MItem = ref<any>({
    binding: 'U',
    bootstrapServerAccountTimeout: 0,
    bootstrapServerIs: false,
    clientHoldOffTime: 1,
    defaultMinPeriod: 1,
    host: '0.0.0.0',
    lifetime: 300,
    notifIfDisabled: true,
    port: 5686,
    securityMode: 'PSK',
    serverCertificate: '',
    serverPublicKey: '',
    shortServerId: 123,
    Form: useForm({
      schemas: LWM2MServerSchemas,
      layout: 'vertical',
      ...modalFormStyleSetting,
      showActionButtonGroup: false,
    }),
  });
  //BootStrap Serve 数据参数
  const BootstrapItem = ref<any>({
    binding: 'U',
    bootstrapServerAccountTimeout: 0,
    bootstrapServerIs: true,
    clientHoldOffTime: 1,
    defaultMinPeriod: 1,
    host: '0.0.0.0',
    lifetime: 300,
    notifIfDisabled: true,
    port: 5686,
    securityMode: 'PSK',
    serverPublicKey: '',
    shortServerId: 123,
    Form: useForm({
      schemas: LWM2MServerSchemas,
      layout: 'vertical',
      ...modalFormStyleSetting,
      showActionButtonGroup: false,
    }),
  });
  //tab页4展示的数据
  let json_string = ref<any>(JSON.stringify(transportConfiguration.value));
  watch(
    () => props.formData,
    (nVal) => {
      if (nVal?.type === 'LWM2M') {
        nVal.bootstrap.forEach((value, index) => {
          nVal.bootstrap[index] = {
            ...value,
            Form: useForm({
              schemas: LWM2MServerSchemas,
              layout: 'vertical',
              ...modalFormStyleSetting,
              showActionButtonGroup: false,
            }),
          };
        });
        emitsValue.value = nVal;
        transportConfiguration.value = emitsValue.value;
      }
    },
    { immediate: true },
  );
  watch(
    () => props.disable,
    (nVal) => {
      isDisable.value = nVal;
    },
    { immediate: true },
  );
  watch(
    () => activeKey.value,
    async (nVal) => {
      if (nVal == 4) {
        json_string.value = await getLWM2MTransportData();
      }
      if (nVal == 3) {
        if (isDisable.value) {
          await setSettingProps({ disabled: true });
          // await setClientSettingProps({ disabled: true });
        }
      }
    },
    {},
  );
  const [
    registerSetting,
    { validate: getSettingValue, setFieldsValue: setFieldsSettingValue, setProps: setSettingProps },
  ] = useForm({
    layout: 'vertical',
    schemas: SettingSchemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  onMounted(async () => {
    await selectLWM2MList();
    if (emitsValue.value && emitsValue.value.type === 'LWM2M') {
      json_string.value = emitsValue.value;
      for (const value of transportConfiguration.value.bootstrap) {
        await value.Form[1].setFieldsValue(value);
      }
      if (isDisable.value) {
        for (const value of transportConfiguration.value.bootstrap) {
          value.Form[1].setProps({ disabled: true });
        }
      }
      if (emitsValue.value.clientLwM2mSettings.psmActivityTimer) {
        let timeData = formatTime(emitsValue.value.clientLwM2mSettings.psmActivityTimer);
        emitsValue.value.clientLwM2mSettings.psmActivityTimer = timeData.time;
        emitsValue.value.clientLwM2mSettings.timeUnitsPsm = timeData.units;
      }
      if (emitsValue.value.clientLwM2mSettings.edrxCycle) {
        let timeData = formatTime(emitsValue.value.clientLwM2mSettings.edrxCycle);
        emitsValue.value.clientLwM2mSettings.edrxCycle = timeData.time;
        emitsValue.value.clientLwM2mSettings.timeUnitsCyc = timeData.units;
      }
      if (emitsValue.value.clientLwM2mSettings.pagingTransmissionWindow) {
        let timeData = formatTime(emitsValue.value.clientLwM2mSettings.pagingTransmissionWindow);
        emitsValue.value.clientLwM2mSettings.pagingTransmissionWindow = timeData.time;
        emitsValue.value.clientLwM2mSettings.timeUnitsTra = timeData.units;
      }
      setFieldsSettingValue(emitsValue.value.clientLwM2mSettings);
      // setClientSettingValue(emitsValue.value.clientLwM2mSettings);
      selectedLwM2MObjects.value = [];
      observeAttrFormat();
      initSelectedLwM2MObjectsArray();
    }
  });
  // 有传进来的数据时，处理emitsValue中的observeAttr
  function observeAttrFormat() {
    const clonedLwM2MList = _.cloneDeep(lwm2mList.value);
    //处理observeAttr.attributeLwm2m
    Object.keys(emitsValue.value.observeAttr.attributeLwm2m).forEach((name) => {
      let nameArray = name.split('/');
      //当前Lwm2m信息
      let currentItem: any = {};
      //当前Lwm2m中实例信息
      let currentInstances: any = {};
      if (nameArray.length === 2) {
        //如果nameArray长度为2，currentItem一定不在selectedLwM2MObjects中
        currentItem = clonedLwM2MList.find((item: any) => item.keyId === nameArray[1]);
        selectedLwM2MObjects.value.push(currentItem);
        selectedLwM2MObjects.value.map((data) => {
          if (data.keyId === nameArray[1]) {
            data.pData = [];
            Object.keys(emitsValue.value.observeAttr.attributeLwm2m[name]).forEach((keyName) => {
              data.pData.push({
                key: keyName,
                number: emitsValue.value.observeAttr.attributeLwm2m[name][keyName],
              });
            });
          }
        });
      }
      if (nameArray.length === 4 || nameArray.length === 3) {
        currentItem = selectedLwM2MObjects.value.find((item) => item.keyId === nameArray[1]);
        if (!currentItem) {
          //如果selectedLwM2MObjects不存在当前的Lwm2m,就从clonedLwM2MList中获取
          let Item = clonedLwM2MList.find((item) => item.keyId === nameArray[1]);
          currentItem = Item;
          selectedLwM2MObjects.value.push(currentItem);
        }
        currentInstances = currentItem.instances.find((item) => item.id == nameArray[2]);
        if (!currentInstances) {
          //如果当前currentItem中不包含currentInstances中匹配的数据,就从clonedLwM2MList中获取
          let Item = _.cloneDeep(clonedLwM2MList.find((item) => item.keyId === nameArray[1]));
          let Instances = _.cloneDeep(Item.instances[0]);
          Instances.id = nameArray[2];
          currentInstances = Instances;
          currentItem.instances.push(currentInstances);
          selectedLwM2MObjects.value.map((obj) => {
            if (obj.keyId === nameArray[1]) {
              obj = currentItem;
            }
          });
        }
        //把相应的数据写到响应的层级下的pData中
        if (nameArray.length === 3) {
          let obj = JSON.parse(JSON.stringify(selectedLwM2MObjects.value));
          obj.map((data) => {
            if (data.keyId === nameArray[1]) {
              data.instances.map((ins) => {
                if (ins.id == nameArray[2]) {
                  ins.pData = [];
                  Object.keys(emitsValue.value.observeAttr.attributeLwm2m[name]).forEach(
                    (keyName) => {
                      ins.pData.push({
                        key: keyName,
                        number: emitsValue.value.observeAttr.attributeLwm2m[name][keyName],
                      });
                    },
                  );
                }
              });
            }
          });
          selectedLwM2MObjects.value = {};
          selectedLwM2MObjects.value = obj;
        }
        if (nameArray.length === 4) {
          let obj = JSON.parse(JSON.stringify(selectedLwM2MObjects.value));
          obj.map((data) => {
            if (data.keyId === nameArray[1]) {
              data.instances.map((ins) => {
                if (ins.id == nameArray[2]) {
                  ins.resources.map((res) => {
                    if (res.id == nameArray[3]) {
                      res.pData = [];
                      Object.keys(emitsValue.value.observeAttr.attributeLwm2m[name]).forEach(
                        (keyName) => {
                          res.pData.push({
                            key: keyName,
                            number: emitsValue.value.observeAttr.attributeLwm2m[name][keyName],
                          });
                        },
                      );
                    }
                  });
                }
              });
            }
          });
          selectedLwM2MObjects.value = {};
          selectedLwM2MObjects.value = obj;
        }
      }
    });
    //处理observeAttr.attribute
    emitsValue.value.observeAttr.attribute.map((name) => {
      let nameArray = name.split('/');

      selectedLwM2MObjects.value.map((data) => {
        if (data.keyId === nameArray[1]) {
          data.instances.map((ins) => {
            if (ins.id == nameArray[2]) {
              ins.resources.map((res) => {
                if (res.id == nameArray[3]) {
                  res.attribute = true;
                }
              });
            }
          });
        }
      });
    });
    //处理observeAttr.observe
    emitsValue.value.observeAttr.observe.map((name) => {
      let nameArray = name.split('/');
      selectedLwM2MObjects.value.map((data) => {
        if (data.keyId === nameArray[1]) {
          data.instances.map((ins) => {
            if (ins.id == nameArray[2]) {
              ins.resources.map((res) => {
                if (res.id == nameArray[3]) {
                  res.observe = true;
                }
              });
            }
          });
        }
      });
    });
    //处理observeAttr.telemetry
    emitsValue.value.observeAttr.telemetry.map((name) => {
      let nameArray = name.split('/');
      selectedLwM2MObjects.value.map((data) => {
        if (data.keyId === nameArray[1]) {
          data.instances.map((ins) => {
            if (ins.id == nameArray[2]) {
              ins.resources.map((res) => {
                if (res.id == nameArray[3]) {
                  res.telemetry = true;
                }
              });
            }
          });
        }
      });
    });
    //处理observeAttr.keyName
    Object.keys(emitsValue.value.observeAttr.keyName).forEach((name) => {
      let nameArray = name.split('/');
      let obj = JSON.parse(JSON.stringify(selectedLwM2MObjects.value));
      obj.map((data) => {
        if (data.keyId === nameArray[1]) {
          data.instances.map((ins) => {
            if (ins.id == nameArray[2]) {
              ins.resources.map((res) => {
                if (res.id == nameArray[3]) {
                  res.keyName = emitsValue.value.observeAttr.keyName[name];
                }
              });
            }
          });
        }
      });
      selectedLwM2MObjects.value = {};
      selectedLwM2MObjects.value = obj;
    });
  }
  // 有传进来的数据时，把选中的LwM2M加入selectedLwM2MObjectsArray，selectedLwM2MObjectsFlag中
  function initSelectedLwM2MObjectsArray() {
    let array: Array<any> = [];
    Object.keys(emitsValue.value.observeAttr.attributeLwm2m).forEach((name) => {
      let nameArray = name.split('/');
      array.push(nameArray[1]);
    });
    array = [...new Set(array)];
    array.map((item) => {
      let index = lwm2mList.value.findIndex((data: any) => (data.keyId = item));
      if (index === -1) {
      } else {
        selectedLwM2MObjectsArray.value.push(index);
        selectedLwM2MObjectsFlag.value.push(index);
      }
    });
  }
  // 获取LwM2M列表
  async function selectLWM2MList() {
    lwm2mList.value = [];
    try {
      let response = await getLWM2MList(params.value);
      lwm2mList.value = response;
    } catch (error) {
      console.error('获取LWM2M数据时报错：', error);
    }
  }

  const addServer = () => {
    transportConfiguration.value.bootstrap.push(_.cloneDeep(LwM2MItem.value));
  };
  //删除服务器配置
  function handleDel(index: number) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除服务器吗？`,
      content: '请注意：确认删除后，服务器配置将无法恢复',
      onOk: () => {
        del(index);
      },
    });
  }
  function del(index: number) {
    transportConfiguration.value.bootstrap.splice(index, 1);
  }
  //根据addNewServeModel的选择，向transportConfiguration.bootstrap推入不同的对象
  function handleChooseType(serverType: string) {
    if (serverType === 'LwM2MServer') {
      transportConfiguration.value.bootstrap.push(_.cloneDeep(LwM2MItem.value));
    } else {
      transportConfiguration.value.bootstrap.push(_.cloneDeep(BootstrapItem.value));
    }
  }
  //添加实例
  function addInstance(data: Recordable) {
    selectedLwM2MObjects.value.map((item) => {
      if (item.id === data.id) {
        item = data;
      }
    });
  }
  // 编辑属性
  function editAttribute(data: Recordable) {
    selectedLwM2MObjects.value.map((item) => {
      if (item.id === data.id) {
        item = data;
      }
    });
  }
  //监听取消勾选 Bootstrap Tab下的包含Bootstrap Serve 更新
  watch(
    () => transportConfiguration.value.bootstrapServerUpdateEnable,
    (newVal, oldVal) => {
      if (oldVal === true && newVal === false) {
        createConfirm({
          iconType: 'info',
          title: `你已经配置了Bootstrap Server,您确定要排除更新吗？`,
          content: '请注意确认更新后Bootstrap Server配置数据将无法恢复',
          onOk: () => {
            const updatedBootstrapList = transportConfiguration.value.bootstrap.filter(
              (server) => !server.bootstrapServerIs,
            );
            transportConfiguration.value.bootstrap = updatedBootstrapList;
          },
        });
      }
    },
  );
  // 打开添加实例弹窗
  function toAddInstance(data: Recordable) {
    openInstanceModal(true, data);
  }
  //打开添加服务器弹窗
  function toAddServer() {
    openModal(true);
  }
  //data是一整个LWM2MObj，level是修改第几层，index是第几个
  function toEditAttribute(data: any, level: number, index?: number, resourcesIndex?: number) {
    data.edit = { level: level, index: index, index1: resourcesIndex };
    openEditAttributeModal(true, data);
  }
  //SELECT change事件
  function handleChange(change: any) {
    selectedLwM2MObjectsArray.value = [];
    change.map((item) => {
      selectedLwM2MObjectsArray.value.push(item);
    });
    if (selectedLwM2MObjectsFlag.value.length < change.length) {
      selectedLwM2MObjects.value.push(_.cloneDeep(lwm2mList.value[change[change.length - 1]]));
    } else {
      let key = selectedLwM2MObjectsFlag.value.filter((item) => !change.includes(item));
      let List = selectedLwM2MObjects.value.filter(
        (item) => !(item.keyId === lwm2mList.value[key].keyId),
      );

      selectedLwM2MObjects.value = List;
    }

    selectedLwM2MObjectsFlag.value = change;
  }
  // 全选
  //1是属性，2是遥测，3是观察者
  function allSelectChange(change: any, data: Recordable, index: number, type: number) {
    let changeData = change.target.checked;
    if (type === 1) {
      data.instances[index].resources.map((item) => {
        item.attribute = changeData;
      });
    }
    if (type === 2) {
      data.instances[index].resources.map((item) => {
        item.telemetry = changeData;
      });
    }
    if (type === 3) {
      data.instances[index].resources.map((item) => {
        if (item.attribute || item.telemetry) {
          item.observe = changeData;
        }
      });
    }
  }
  // 是否是部分选中，checkbox的半选状态
  function isPartiallySelected(data: Recordable, index: number, type: number) {
    let attribute = data.instances[index].resources.some((item) => item.attribute);
    let telemetry = data.instances[index].resources.some((item) => item.telemetry);
    let observe = data.instances[index].resources.some((item) => item.observe);
    if (type === 1) {
      return attribute;
    }
    if (type === 2) {
      return telemetry;
    }
    if (type === 3) {
      return observe;
    }
    if (type === 4) {
      return !(attribute || telemetry || observe);
    }
  }
  //格式化时间
  function formatTime(time: number) {
    if (time >= 3600000 && time % 360000 === 0) {
      const hours = time / 3600000;
      return { time: hours, units: '小时' };
    } else if (time >= 60000 && time % 60000 === 0) {
      const minutes = time / 60000;
      return { time: minutes, units: '分钟' };
    } else if (time >= 1000 && time % 1000 === 0) {
      const seconds = time / 1000;
      return { time: seconds, units: '秒' };
    } else {
      return { time: time, units: '毫秒' };
    }
  }
  //把不同的单位都化成毫秒(时间，单位)
  function convertTime(time: number, units: string) {
    if (units === '小时') {
      return time * 3600000;
    } else if (units === '分钟') {
      return time * 60000;
    } else if (units === '秒') {
      return time * 1000;
    } else {
      return time;
    }
  }
  // 整合数据
  async function getLWM2MTransportData() {
    // tab页3表单验证
    try {
      const res = await getSettingValue();
      delete res.clientSettings;
      transportConfiguration.value.clientLwM2mSettings = res;
      //clientOnlyObserveAfterConnect添加的时候默认是1
      transportConfiguration.value.clientLwM2mSettings.clientOnlyObserveAfterConnect = 1;
    } catch (error) {
      activeKey.value = '3';
      return null;
    }
    let serverData: any = [];
    try {
      for (const item of transportConfiguration.value.bootstrap) {
        const values = await item.Form[1].validate();
        serverData.push(values);
      }
    } catch (e) {
      activeKey.value = '2';
      return null;
    }
    transportConfiguration.value.bootstrap.forEach((_value, index) => {
      Object.assign(transportConfiguration.value.bootstrap[index], serverData[index]);
    });
    //把关于时间的参数单位都换算成毫秒
    let client = transportConfiguration.value.clientLwM2mSettings;
    client.psmActivityTimer = convertTime(client.psmActivityTimer, client.timeUnitsPsm);
    client.edrxCycle = convertTime(client.edrxCycle, client.timeUnitsCyc);
    client.pagingTransmissionWindow = convertTime(
      client.pagingTransmissionWindow,
      client.timeUnitsTra,
    );
    delete client.timeUnitsPsm;
    delete client.timeUnitsCyc;
    delete client.timeUnitsTra;
    transportConfiguration.value.clientLwM2mSettings = client;
    //tabs页1数据整合
    transportConfiguration.value.observeAttr = {
      attribute: [],
      attributeLwm2m: {},
      keyName: {},
      observe: [],
      telemetry: [],
    };
    selectedLwM2MObjects.value.map((item) => {
      if (item.pData) {
        let name = '/' + item.keyId;
        transportConfiguration.value.observeAttr.attributeLwm2m[name] = {};
        item.pData.map((pItem) => {
          Reflect.set(
            transportConfiguration.value.observeAttr.attributeLwm2m[name],
            pItem.key,
            pItem.number,
          );
        });
      }
      item.instances.map((instances) => {
        if (instances.pData) {
          let name = '/' + item.keyId + '/' + instances.id;
          transportConfiguration.value.observeAttr.attributeLwm2m[name] =
            transportConfiguration.value.observeAttr.attributeLwm2m[name] || {};
          instances.pData.map((pItem) => {
            Reflect.set(
              transportConfiguration.value.observeAttr.attributeLwm2m[name],
              pItem.key,
              pItem.number,
            );
          });
        }
        instances.resources.map((resource) => {
          let name = '/' + item.keyId + '/' + instances.id + '/' + resource.id;
          if (resource.pData && (resource.attribute || resource.telemetry)) {
            transportConfiguration.value.observeAttr.attributeLwm2m[name] =
              transportConfiguration.value.observeAttr.attributeLwm2m[name] || {};
            resource.pData.map((pItem) => {
              Reflect.set(
                transportConfiguration.value.observeAttr.attributeLwm2m[name],
                pItem.key,
                pItem.number,
              );
            });
          }
          if (resource.attribute) {
            transportConfiguration.value.observeAttr.attribute.push(name);
          }
          if (resource.telemetry) {
            transportConfiguration.value.observeAttr.telemetry.push(name);
          }
          if (resource.observe) {
            transportConfiguration.value.observeAttr.observe.push(name);
          }
          if (resource.attribute || resource.telemetry || resource.observe) {
            Reflect.set(transportConfiguration.value.observeAttr.keyName, name, resource.keyName);
          }
        });
      });
    });
    return transportConfiguration.value;
  }

  defineExpose({
    getLWM2MTransportData,
  });
</script>

<style lang="less" scoped>
  .ant-collapse :deep(.ant-collapse-item > .ant-collapse-header) {
    align-items: center;
  }
</style>
